package com.lagou.elasticJob;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.lagou.util.JdbcUtil;

import java.util.List;
import java.util.Map;

/**
 * 需求:
 * 每隔两秒钟执行一次定时任务（resume表中未归档的数据归档到resume_bak表中，每次归档1条记录）
 */
public class BackupJob implements SimpleJob {

    private static final String SELECT_SQL = "select * from resume where state='未归档' limit 1";
    private static final String UPDATE_SQL = "update resume set state='已归档' where id=?";
    private static final String INSERT_SQL = "insert into resume_bak select * from resume where id=?";

    // 定时任务每执行一次都会执行如下的逻辑
    @Override
    public void execute(ShardingContext shardingContext) {
        // 查询出一条数据
        List<Map<String, Object>> list = JdbcUtil.executeQuery(SELECT_SQL);
        if(list == null || list.size() == 0) {
            System.out.println("无待归档任务");
            return;
        }
        Map<String, Object> stringObjectMap = list.get(0);
        Long id = (Long) stringObjectMap.get("id");
        // 打印任务信息
        printInfo(stringObjectMap, id);
        // 更改任务状态
        JdbcUtil.executeUpdate(UPDATE_SQL,id);
        // 归档这条记录
        JdbcUtil.executeUpdate(INSERT_SQL,id);
    }

    private void printInfo(Map<String, Object> stringObjectMap, Long id) {
        String name = (String) stringObjectMap.get("name");
        String education = (String) stringObjectMap.get("education");
        // 打印出这条记录
        System.out.println("======>>>id：" + id + " name：" + name + " education：" + education);
    }

}
